package com.olap.starter.util.sql;


import com.olap.starter.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//解析sql中的表字段
public class SqlParseTableFiled {
    public static void main(String[] args) {
        String sql = "SELECT\n" +
                "  `furnace_batch_no`,\n" +
                "  SUM(`mat_num`) AS `mat_num`,\n" +
                "  SUM(`mat_act_wt`) AS `mat_act_wt`\n" +
                "FROM\n" +
                "  `mat_bw01`\n" +
                "WHERE\n" +
                "  `prod_type` = '7'\n" +
                "GROUP BY\n" +
                "  `furnace_batch_no`";
        execute(sql);
    }
    public static void execute(String sql) {
        List<String> columnAsColumnStr = getColumnAsColumnStr(sql);
        System.out.println(columnAsColumnStr);
    }

    public static List<String> getColumnAsColumnStr(String sql) {

        List<String> columnAsColumnStrList = new ArrayList<>();
        if (StringUtils.isEmpty(sql)) {
            throw new RuntimeException("sql语句为空");
        }
        sql = sql.toLowerCase();
        int index = 0;
        int fromIndex = 0;
        while (index >= 0) {
            index = sql.indexOf("from", fromIndex);

            if (index - 1 >= 0 && index + 4 < sql.length()) {
                char beforeChar = sql.charAt(index - 1);
                char afterChar = sql.charAt(index + 4);
                fromIndex = index + 4;
                if ((beforeChar == '\n' || beforeChar == ' ' || beforeChar == '\t' || beforeChar == '\r')
                        && (afterChar == '\n' || afterChar == ' ' || afterChar == '\t' || afterChar == '\r' || afterChar == '(')) {
                    break;
                }
            } else {
                index = -1;
            }
        }

        if (index >= 0) {
            int startIndex = sql.indexOf("select");

            if (startIndex < 0) {
                throw new RuntimeException("开头缺少select关键字");
            }

            if (sql.length() < startIndex + 6) {
                throw new RuntimeException("sql语句不完整");
            }

            String partSql = sql.substring(startIndex + 6, index);

            String regex = ",(?=[^()]*\\))";
            partSql = partSql.replaceAll(regex, " ");
            columnAsColumnStrList.addAll(Arrays.asList(partSql.split(",")));
        }

        return columnAsColumnStrList;
    }
}
